const express = require("express");
const router = express.Router();
const GoodsModel = require('../db/model/goodsModel');
const jwt = require("jsonwebtoken");

/**
 * @api {post} /createGoods 添加商品信息
 * @apiName createGoods
 * @apiGroup Goods
 *
 * @apiParam {String} img 商品图片
 * @apiParam {String} price 商品价格
 * @apiParam {String} title 商品标题
 * @apiParam  {String} classify 商品分类

 * @apiSuccess {Number} code code码 0  成功 -1 失败.
 * @apiSuccess {String} msg  返回信息.
 * @apiSuccess {Arrary} list  商品列表.
 */
 router.post('/createGoods', async (req, res) => {
    // 接受数据
    const { img , classify , price, title } = req.body;
    const updateInfo = await GoodsModel.insertMany({ img ,classify, price , title })
  console.log(updateInfo)
    if(updateInfo) {
      return res.send({ codo:0, msg: "商品添加success"})
    }
    return res.send({ codo:-1, msg: "商品添加defeat"})
  });
  


  /**
 * @api {post} /getGoods 查询商品信息
 * @apiName getGoods
 * @apiGroup Goods
 *
 * @apiParam {Number} page 页码数.
 * @apiParam {Number} pageSize 每页条数.

 * @apiSuccess {Number} code code码 0  成功 -1 失败.
 * @apiSuccess {String} msg  返回信息.
 * @apiSuccess {Arrary} list  商品列表.
 */
   router.post('/getGoods',async (req,res) => {
    const { page =1,pageSize =10} = req.query
    const list =await GoodsModel.find().limit(pageSize).skip((page-1)*pageSize);
    if(list) {
      return res.send({ code:0,msg:"商品查询ok",list})
    }
    return res.send({ code:-1,msg:"商品查询nook"})
  })

  /**
 * @api {post} /updateGoods 修改商品信息
 * @apiName updateGoods
 * @apiGroup Goods
 *
 * @apiParam {String} img 商品图片
 * @apiParam {String} price 商品价格
 * @apiParam {String} title 商品标题
 * @apiParam  {String} classify 商品分类

 * @apiSuccess {Number} code code码 0  成功 -1 失败.
 * @apiSuccess {String} msg  返回信息.
 * @apiSuccess {Arrary} list  商品列表.
 */
 router.post('/updateGoods', async (req, res) => {
    // 接受数据
    const {img , classify , price, title } = req.body;
    const updateInfo = await GoodsModel.findByIdAndUpdate({ img ,classify, price , title  })
  console.log(updateInfo)
    if(updateInfo) {
      return res.send({ codo:0, msg: "商品修改success"})
    }
      return res.send({ codo:-1, msg: "商品修改defeat"})
  });
  
  /**
 * @api {post} /delgoods 删除商品信息
 * @apiName delgoods
 * @apiGroup Goods
 *
 * @apiParam {String} id 商品id

 * @apiSuccess {Number} code code码 0  成功 -1 失败.
 * @apiSuccess {String} msg  返回信息.
 * @apiSuccess {Arrary} list  商品列表.
 */
// 删除用户数据
router.post('/delgoods', async (req, res) => {
    // 接受数据
    const { id } = req.body;
    const delInfo = await GoodsModel.findByIdAndDelete(id)
    if(delInfo) {
      return res.send({ codo:0, msg: "商品删除ok"})
    }
    return res.send({ codo:-1, msg: "商品删除失败"})
  
  });
  
module.exports = router;